<template>
  <div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="businessArea" label="地区" width="120"></el-table-column>
      <el-table-column v-for="category in serviceCategories"
                       :key="category"
                       :prop="category"
                       :label="categoryMap[category] || category">
      </el-table-column>
      <el-table-column prop="total" label="总计"></el-table-column>
    </el-table>
  </div>
</template>

<script setup name="Orderrecords">
import { listOrders, getOrders, delOrders, addOrders, updateOrders,selectOrderBy } from "@/api/masterrabbit-kaixuan/orders";
const {proxy} = getCurrentInstance();

const {sys_service_type} = proxy.useDict('sys_service_type');


const orderrecordsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeOrderTime = ref([]);
const daterangeAppointmentTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recordId: null,
    orderNumber: null,
    serviceCategory: null,
    serviceShop: null,
    orderTime: null,
    appointmentTime: null,
    vehicleInfo: null,
    remarks: null,
    serviceName: null,
    totalAmount: null,
    discountAmount: null,
    actualAmount: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeOrderTime && '' != daterangeOrderTime) {
    queryParams.value.params["beginOrderTime"] = daterangeOrderTime.value[0];
    queryParams.value.params["endOrderTime"] = daterangeOrderTime.value[1];
  }
  if (null != daterangeAppointmentTime && '' != daterangeAppointmentTime) {
    queryParams.value.params["beginAppointmentTime"] = daterangeAppointmentTime.value[0];
    queryParams.value.params["endAppointmentTime"] = daterangeAppointmentTime.value[1];
  }
  listOrders(queryParams.value).then(response => {
    orderrecordsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    orderNumber: null,
    serviceCategory: null,
    serviceShop: null,
    orderTime: null,
    appointmentTime: null,
    vehicleInfo: null,
    remarks: null,
    serviceName: null,
    totalAmount: null,
    discountAmount: null,
    actualAmount: null
  };
  proxy.resetForm("orderrecordsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeOrderTime.value = [];
  daterangeAppointmentTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getOrders(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderrecordsRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除订单记录编号为"' + _recordIds + '"的数据项？').then(function() {
    return delOrders(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('masterrabbit-kaixuan/orderrecords/export', {
    ...queryParams.value
  }, `orderrecords_${new Date().getTime()}.xlsx`)
}


const rawData = ref([]); // API 原始数据
const tableData = ref([]); // 处理后的表格数据
const serviceCategories = ref([]); // 动态行字段（订单类型）

// 订单类型映射
const categoryMap = {
  "1": "车辆维修",
  "2": "汽车保养",
  "3": "专业洗车"
};

// 获取数据
async function getAllList() {
  try {
    const response = await selectOrderBy();
    console.log("API 返回数据:", response);
    rawData.value = response;
    generateTableData();
  } catch (error) {
    console.error("数据加载失败", error);
  }
}

// 处理数据生成表格
function generateTableData() {
  let table = {};
  let categorySet = new Set();

  rawData.value.forEach(order => {
    let area = order.merchants?.businessArea || "未知区域";
    let category = order.serviceCategory || "未知类别";

    categorySet.add(category);

    if (!table[area]) {
      table[area] = { businessArea: area, total: 0 };
    }
    if (!table[area][category]) {
      table[area][category] = 0;
    }

    table[area][category] += 1;
    table[area]["total"] += 1;
  });

  // 计算各订单类型的总计
  let totalRow = { businessArea: "总计", total: 0 };
  categorySet.forEach(category => {
    totalRow[category] = 0;
  });

  Object.keys(table).forEach(area => {
    categorySet.forEach(category => {
      totalRow[category] += (table[area][category] || 0);
    });
    totalRow["total"] += table[area]["total"];
  });

  // 设置表格数据
  tableData.value = Object.values(table);
  tableData.value.push(totalRow);
  serviceCategories.value = Array.from(categorySet);
}

onMounted(() => {
  getAllList();
});


</script>
